<template>
  <div class="behavior-analysis-container">
    <el-card shadow="never">
      <el-tabs v-model="activeTab" type="card">
        <!-- 转化率分析标签页 -->
        <el-tab-pane label="转化率分析" name="conversion">
          <div class="analysis-header">
            <div class="header-title">
              <el-icon><TrendCharts /></el-icon>
              <span>转化率分析</span>
            </div>
            <div class="header-actions">
              <el-date-picker
                  v-model="conversionDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="fetchConversionData"
              />
              <el-button type="primary" @click="exportConversionData">
                <el-icon><Download /></el-icon>导出数据
              </el-button>
            </div>
          </div>

          <el-row :gutter="20" class="summary-cards">
            <el-col :span="6">
              <el-card shadow="hover">
                <div class="card-content">
                  <div class="card-title">总访问量</div>
                  <div class="card-value">{{ summaryData.totalVisits }}</div>
                  <div class="card-compare">
                    <span :class="summaryData.visitTrend >= 0 ? 'up' : 'down'">
                      <el-icon :name="summaryData.visitTrend >= 0 ? 'Top' : 'Bottom'" />
                      {{ Math.abs(summaryData.visitTrend) }}%
                    </span>
                    同比
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <div class="card-content">
                  <div class="card-title">总签约量</div>
                  <div class="card-value">{{ summaryData.totalSigns }}</div>
                  <div class="card-compare">
                    <span :class="summaryData.signTrend >= 0 ? 'up' : 'down'">
                      <el-icon :name="summaryData.signTrend >= 0 ? 'Top' : 'Bottom'" />
                      {{ Math.abs(summaryData.signTrend) }}%
                    </span>
                    同比
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <div class="card-content">
                  <div class="card-title">平均转化率</div>
                  <div class="card-value">{{ summaryData.avgConversionRate }}%</div>
                  <div class="card-compare">
                    <span :class="summaryData.rateTrend >= 0 ? 'up' : 'down'">
                      <el-icon :name="summaryData.rateTrend >= 0 ? 'Top' : 'Bottom'" />
                      {{ Math.abs(summaryData.rateTrend) }}%
                    </span>
                    同比
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <div class="card-content">
                  <div class="card-title">最佳区域</div>
                  <div class="card-value">{{ summaryData.bestRegion }}</div>
                  <div class="card-compare">
                    转化率 {{ summaryData.bestRegionRate }}%
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <el-row :gutter="20" class="chart-row">
            <el-col :span="16">
              <el-card shadow="hover">
                <div class="chart-title">各区域转化率对比</div>
                <div class="chart-container">
                  <!-- 这里应该放置echarts图表 -->
                  <div ref="conversionChart" style="width: 100%; height: 400px;"></div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="hover">
                <div class="chart-title">转化率排行榜</div>
                <el-table :data="conversionRates" height="400" style="width: 100%">
                  <el-table-column prop="region" label="区域" width="120" />
                  <el-table-column prop="visitCount" label="访问量" width="100" />
                  <el-table-column prop="signCount" label="签约量" width="100" />
                  <el-table-column label="转化率" width="120">
                    <template #default="{ row }">
                      <el-tag :type="getRateTagType(row.conversionRate)">
                        {{ row.conversionRate }}%
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120">
                    <template #default="{ row }">
                      <el-button
                          size="small"
                          @click="optimizeExposure(row.region)"
                          :disabled="row.conversionRate >= 30"
                      >
                        {{ row.conversionRate >= 30 ? '表现良好' : '增加曝光' }}
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>

        <!-- 沉默用户召回标签页 -->
        <el-tab-pane label="沉默用户召回" name="inactive">
          <div class="analysis-header">
            <div class="header-title">
              <el-icon><User /></el-icon>
              <span>沉默用户召回</span>
            </div>
            <div class="header-actions">
              <el-select
                  v-model="inactiveDaysThreshold"
                  placeholder="沉默天数"
                  style="width: 120px"
                  @change="fetchInactiveUsers"
              >
                <el-option label="30天以上" value="30" />
                <el-option label="60天以上" value="60" />
                <el-option label="90天以上" value="90" />
              </el-select>
              <el-button type="primary" @click="batchRecall">
                <el-icon><Message /></el-icon>批量召回
              </el-button>
            </div>
          </div>

          <el-table
              :data="inactiveUsers"
              style="width: 100%"
              v-loading="inactiveLoading"
              @selection-change="handleInactiveSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="username" label="用户名" width="120" />
            <el-table-column prop="phone" label="手机号" width="130" />
            <el-table-column prop="lastLogin" label="最后登录" width="150" />
            <el-table-column prop="inactiveDays" label="沉默天数" width="100">
              <template #default="{ row }">
                <el-tag type="danger">{{ row.inactiveDays }}天</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="lastAction" label="最后行为" width="120" />
            <el-table-column prop="interest" label="兴趣标签" width="150">
              <template #default="{ row }">
                <el-tag
                    v-for="tag in row.interest.split(',')"
                    :key="tag"
                    style="margin-right: 5px; margin-bottom: 5px"
                >
                  {{ tag }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="sendRecallNotification(row)">
                  发送通知
                </el-button>
                <el-button size="small" @click="viewUserDetail(row.id)">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
              v-model:current-page="inactivePage"
              v-model:page-size="inactivePageSize"
              :total="inactiveTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="fetchInactiveUsers"
              @current-change="fetchInactiveUsers"
              style="margin-top: 20px"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 召回通知对话框 -->
    <el-dialog
        v-model="recallDialogVisible"
        title="发送召回通知"
        width="600px"
    >
      <el-form :model="recallForm" label-width="80px">
        <el-form-item label="通知类型">
          <el-radio-group v-model="recallForm.noticeType">
            <el-radio label="sms">短信通知</el-radio>
            <el-radio label="email">邮件通知</el-radio>
            <el-radio label="app">APP推送</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="通知内容">
          <el-input
              v-model="recallForm.content"
              type="textarea"
              :rows="5"
              placeholder="请输入通知内容"
          />
        </el-form-item>
        <el-form-item label="优惠活动">
          <el-select
              v-model="recallForm.couponId"
              placeholder="选择优惠活动"
              style="width: 100%"
          >
            <el-option
                v-for="item in couponOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="recallDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRecall">确认发送</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { TrendCharts, Download, User, Message } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'

// 当前激活的标签页
const activeTab = ref('conversion')

// 转化率分析相关数据
const conversionDateRange = ref(['2023-06-01', '2023-06-30'])
const conversionRates = ref([])
const summaryData = ref({
  totalVisits: 0,
  totalSigns: 0,
  avgConversionRate: 0,
  visitTrend: 0,
  signTrend: 0,
  rateTrend: 0,
  bestRegion: '',
  bestRegionRate: 0
})
const conversionChart = ref(null)

// 沉默用户召回相关数据
const inactiveDaysThreshold = ref('30')
const inactiveUsers = ref([])
const inactiveLoading = ref(false)
const inactivePage = ref(1)
const inactivePageSize = ref(10)
const inactiveTotal = ref(0)
const selectedInactiveUsers = ref([])

// 召回通知对话框
const recallDialogVisible = ref(false)
const recallForm = ref({
  noticeType: 'sms',
  content: '',
  couponId: ''
})
const couponOptions = ref([
  { id: '1', name: '新用户首月租金立减500元' },
  { id: '2', name: '签约即送搬家服务' },
  { id: '3', name: '推荐好友得现金奖励' }
])

// 获取转化率数据（使用死数据）
const fetchConversionData = () => {
  // 模拟API返回的转化率数据
  const mockData = {
    totalVisits: 12800,
    newUsers: 3200,
    conversionRate: 25,
    regionData: [
      { region: '朝阳区', visitCount: 3200, signCount: 960, conversionRate: 30 },
      { region: '海淀区', visitCount: 2800, signCount: 560, conversionRate: 20 },
      { region: '东城区', visitCount: 2200, signCount: 330, conversionRate: 15 },
      { region: '西城区', visitCount: 1800, signCount: 288, conversionRate: 16 },
      { region: '丰台区', visitCount: 1500, signCount: 225, conversionRate: 15 },
      { region: '通州区', visitCount: 300, signCount: 60, conversionRate: 20 }
    ]
  }

  // 填充汇总数据
  summaryData.value = {
    totalVisits: mockData.totalVisits,
    totalSigns: mockData.newUsers,
    avgConversionRate: mockData.conversionRate,
    visitTrend: 12, // 假设同比增长12%
    signTrend: 8,   // 假设同比增长8%
    rateTrend: 5,   // 假设同比增长5%
    bestRegion: mockData.regionData[0].region,
    bestRegionRate: mockData.regionData[0].conversionRate
  }

  conversionRates.value = mockData.regionData

  // 渲染图表
  nextTick(() => {
    renderConversionChart()
  })
}

// 渲染转化率图表
const renderConversionChart = () => {
  if (!conversionChart.value) return

  const chart = echarts.init(conversionChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['访问量', '签约量', '转化率']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: conversionRates.value.map(item => item.region)
    },
    yAxis: [
      {
        type: 'value',
        name: '数量',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '转化率',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '访问量',
        type: 'bar',
        data: conversionRates.value.map(item => item.visitCount)
      },
      {
        name: '签约量',
        type: 'bar',
        data: conversionRates.value.map(item => item.signCount)
      },
      {
        name: '转化率',
        type: 'line',
        yAxisIndex: 1,
        data: conversionRates.value.map(item => item.conversionRate)
      }
    ]
  }

  chart.setOption(option)
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 获取沉默用户数据（使用死数据）
const fetchInactiveUsers = () => {
  inactiveLoading.value = true

  // 模拟API返回的沉默用户数据
  const mockData = {
    total: 20,
    list: [
      {
        id: 1,
        username: '张三',
        phone: '13800138001',
        lastLogin: '2023-05-15',
        inactiveDays: 45,
        lastAction: '浏览房源',
        interest: '两居室,朝阳区,近地铁'
      },
      {
        id: 2,
        username: '李四',
        phone: '13800138002',
        lastLogin: '2023-05-10',
        inactiveDays: 50,
        lastAction: '收藏房源',
        interest: '三居室,海淀区,带阳台'
      },
      {
        id: 3,
        username: '王五',
        phone: '13800138003',
        lastLogin: '2023-05-05',
        inactiveDays: 55,
        lastAction: '预约看房',
        interest: '一居室,东城区,低租金'
      },
      {
        id: 4,
        username: '赵六',
        phone: '13800138004',
        lastLogin: '2023-05-01',
        inactiveDays: 59,
        lastAction: '浏览房源',
        interest: '两居室,西城区,拎包入住'
      },
      {
        id: 5,
        username: '孙七',
        phone: '13800138005',
        lastLogin: '2023-04-25',
        inactiveDays: 65,
        lastAction: '咨询价格',
        interest: '三居室,丰台区,有车位'
      },
      {
        id: 6,
        username: '周八',
        phone: '13800138006',
        lastLogin: '2023-04-20',
        inactiveDays: 70,
        lastAction: '浏览房源',
        interest: '一居室,通州区,性价比高'
      },
      {
        id: 7,
        username: '吴九',
        phone: '13800138007',
        lastLogin: '2023-04-15',
        inactiveDays: 75,
        lastAction: '收藏房源',
        interest: '两居室,朝阳区,配套齐全'
      },
      {
        id: 8,
        username: '郑十',
        phone: '13800138008',
        lastLogin: '2023-04-10',
        inactiveDays: 80,
        lastAction: '预约看房',
        interest: '三居室,海淀区,近学校'
      },
      {
        id: 9,
        username: '钱十一',
        phone: '13800138009',
        lastLogin: '2023-04-05',
        inactiveDays: 85,
        lastAction: '浏览房源',
        interest: '一居室,东城区,精装修'
      },
      {
        id: 10,
        username: '孙十二',
        phone: '13800138010',
        lastLogin: '2023-04-01',
        inactiveDays: 90,
        lastAction: '咨询价格',
        interest: '两居室,西城区,近商圈'
      }
    ]
  }

  // 根据分页参数截取数据
  const startIndex = (inactivePage.value - 1) * inactivePageSize.value
  const endIndex = Math.min(startIndex + inactivePageSize.value, mockData.total)

  inactiveUsers.value = mockData.list.slice(0, endIndex - startIndex)
  inactiveTotal.value = mockData.total
  inactiveLoading.value = false
}

// 导出转化率数据
const exportConversionData = () => {
  ElMessage.success('导出功能已触发，实际项目中会生成并下载数据')
}

// 批量召回
const batchRecall = () => {
  if (selectedInactiveUsers.value.length === 0) {
    ElMessage.warning('请至少选择一条数据')
    return
  }
  recallForm.value = {
    noticeType: 'sms',
    content: '尊敬的客户，我们为您准备了专属优惠活动，欢迎回来查看最新房源！',
    couponId: '1'
  }
  recallDialogVisible.value = true
}

// 发送单个召回通知
const sendRecallNotification = (user) => {
  selectedInactiveUsers.value = [user]
  recallForm.value = {
    noticeType: 'sms',
    content: `尊敬的${user.username}，我们为您准备了专属优惠活动，欢迎回来查看最新房源！`,
    couponId: '1'
  }
  recallDialogVisible.value = true
}

// 确认发送召回通知
const confirmRecall = () => {
  if (selectedInactiveUsers.value.length === 0) {
    ElMessage.warning('请选择要发送通知的用户')
    return
  }

  ElMessage.success(`已向${selectedInactiveUsers.value.length}位用户发送召回通知`)
  recallDialogVisible.value = false
}

// 查看用户详情
const viewUserDetail = (userId) => {
  ElMessage.info(`查看用户详情: ID=${userId}`)
}

// 优化区域曝光
const optimizeExposure = (region) => {
  ElMessageBox.confirm(`确定要增加${region}区域的房源曝光吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(`${region}区域曝光已增加`)
  }).catch(() => {})
}

// 获取转化率标签类型
const getRateTagType = (rate) => {
  if (rate >= 30) return 'success'
  if (rate >= 20) return 'warning'
  return 'danger'
}

// 处理沉默用户选择变化
const handleInactiveSelectionChange = (selection) => {
  selectedInactiveUsers.value = selection
}

// 初始化加载数据
onMounted(() => {
  fetchConversionData()
  fetchInactiveUsers()
})
</script>

<style scoped lang="scss">
.behavior-analysis-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.analysis-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .header-title {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: bold;

    .el-icon {
      margin-right: 8px;
      font-size: 20px;
    }
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }
}

.summary-cards {
  margin-bottom: 20px;

  .card-content {
    padding: 15px;

    .card-title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 10px;
    }

    .card-value {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .card-compare {
      font-size: 12px;
      color: #909399;

      .up {
        color: #67c23a;
      }

      .down {
        color: #f56c6c;
      }

      .el-icon {
        font-size: 12px;
      }
    }
  }
}

.chart-row {
  margin-bottom: 20px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.chart-container {
  height: 400px;
}

.up {
  color: #67c23a;
}

.down {
  color: #f56c6c;
}
</style>